package cn.springcloud.fix.common.core.config;

import cn.springcloud.fix.common.core.interceptors.UserContextInterceptor;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

/**
 * ribbon负载均衡配置
 * ribbon有7种策略，随机、轮询、最小并发、响应时间加权等策略
 */
@Configuration
public class RibbonConfig {

    @Bean
    public IRule ribbonRule() {
        return new RandomRule();
    }

    /**
     * 添加LoadBalanced，使RestTemplate已负载均衡的方式调用服务
     */
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getInterceptors().add(new UserContextInterceptor());
        return restTemplate;
    }
}
